package com.example.base

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.*

/**  协程 生命周期 监听  **/
class CoroutineLifecycleListener(private val deferred: Deferred<*>) : LifecycleObserver {
    @Suppress("unused")
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun cancelCoroutine() {
        if (!deferred.isCancelled) {
            deferred.cancel()
        }
    }
}

/**  在 IO 线程中处理一段代码  **/
fun <T> LifecycleOwner.loadAsync(loader: () -> T): Deferred<T> {
    val deferred = GlobalScope.async(context = Dispatchers.IO, start = CoroutineStart.LAZY) {
        loader()
    }

    lifecycle.addObserver(CoroutineLifecycleListener(deferred))
    return deferred
}

/**  在 主线程中 处理一段代码  **/
infix fun <T> Deferred<T>.thenInMain(block: (T) -> Unit): Job {
    return GlobalScope.launch(context = Dispatchers.Main) {
        block(this@thenInMain.await())
    }
}